﻿using System;
using System.Collections.Concurrent;
using System.Threading;

namespace Quail
{
    /// <summary>
    /// A simple concurrent queue with an attached semaphore.  Useful for worker queues
    /// </summary>
    /// <typeparam name="T">Type to store in the Queue</typeparam>
    public class WaitableConcurrentQueue<T> : IDisposable
    {
        private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
        private readonly Semaphore _sem = new Semaphore(0, int.MaxValue);

        ~WaitableConcurrentQueue()
        {
            Dispose(false);
        }

        /// <summary>
        /// Enqueues an item into the queue and signals the WaitOn handle
        /// </summary>
        /// <param name="item">An item to enqueue</param>
        public void Enqueue(T item)
        {
            _queue.Enqueue(item);
            _sem.Release();
        }

        /// <summary>
        /// Removes an item from the queue.  This should only be called when WaitOn.WaitOne() returns true.
        /// </summary>
        /// <returns>The item in the queue</returns>
        public T Dequeue()
        {
            T r;
            if (!_queue.TryDequeue(out r))
                throw new IndexOutOfRangeException("Queue is empty!");

            return r;
        }

        /// <summary>
        /// Gets a handle to wait on
        /// </summary>
        public WaitHandle WaitOn
        {
            get { return _sem; }
        }

        /// <summary>
        /// Gets the count of items in the queue
        /// </summary>
        public int Count
        {
            get { return _queue.Count; }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _sem.Dispose();
            }
        }
    }
}
